package de.graph.document;

import java.io.Serializable;
import java.lang.ref.SoftReference;
import java.util.Set;

import de.graph.document.impl.DocumentKey;
import de.graph.document.impl.DocumentManagerImpl;

public abstract class DocumentFassade implements Serializable {

    private static final long serialVersionUID = -6529401771607402840L;

    private DocumentKey documentKey;
    
    private transient SoftReference<Document> documentRef;

    protected DocumentFassade(final Document document) {
        this.documentKey = new DocumentKey(document.getId());
        this.documentRef = new SoftReference<Document>(document);
    }

    public <ValueType> ValueType getProperty(String key) {
        return getDocumentLazy().getProperty(key);
    }

    public <ValueType> ValueType getProperty(String name, ValueType defaultValue) {
        return getDocumentLazy().getProperty(name, defaultValue);
    }

    public <ValueType> void setProperty(String key, ValueType value) {
        getDocumentLazy().setProperty(key, value);
    }

    public <ValueType> ValueType removeProperty(String key) {
        return getDocumentLazy().removeProperty(key);
    }

    public Set<String> getPropertyKeys() {
        return getDocumentLazy().getPropertyKeys();
    }

    public void clear() {
        getDocumentLazy().clear();
    }

    @Override
    public int hashCode() {
        return getDocumentLazy().hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (!(obj instanceof DocumentFassade)) {
            return false;
        }

        return getDocumentLazy().equals(((DocumentFassade) obj).getDocumentLazy());
    }
    
    private Document getDocumentLazy() {
        if (documentRef == null || documentRef.get() == null) {
            DocumentManager documentManager = DocumentManagerImpl.getInstance();
            
            this.documentRef = new SoftReference<Document>(documentManager.getDocument(documentKey));
        }
        
        return documentRef.get();
    }
}
